package springmvc.components.view;

import springmvc.config.WebConfig;

import java.io.File;

/**
 * @author cg
 * @date 2023/6/16 16:48
 */

/**
 * 负责将字符串封装成对应的视图文件
 */
public class ViewResolver {
    private WebConfig webConfig;
    //只保存视图的文件夹名
    private String templateDirPath;

    //能解析的后缀名
    private String[] suffixList = new String[]{".html"};


    public ViewResolver(String templateDirPath) {
        this.templateDirPath = templateDirPath;
    }


    /**
     * 将视图文件名解析成对应的视图文件
     */
    public View resolveViewName(String viewName) {
        //如果没有携带后缀则添加后缀
        int endIndex = viewName.lastIndexOf(".");
        if (endIndex == -1) {
            //添加后缀
            for (String suffix : suffixList) {
                String realViewName = templateDirPath + viewName + suffix;
                File viewFile = new File(realViewName);
                if (viewFile.exists()) {
                    return new View(viewFile);
                }
            }
            return null;
        } else {
            File viewFile = new File(this.templateDirPath + viewName);
            if (viewFile.exists()) {
                return new View(viewFile);
            } else return null;
        }
    }

    public String getTemplateDirPath() {
        return templateDirPath;
    }

    public void setTemplateDirPath(String templateDirPath) {
        this.templateDirPath = templateDirPath;
    }


}
